package handler

import (
	"github.com/gin-gonic/gin"
	"live-broadcast/dao"
	"live-broadcast/model"
	"live-broadcast/pkg/jwt"
	"live-broadcast/request"
	"live-broadcast/response"
)

const JWT_USER_DON = "2210A"

func Register(c *gin.Context) {
	var data request.RegisterAdd
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	User := model.User{

		Name:     data.Name,
		Password: data.Password,
		Type:     1,
	}
	dao.Create(&User)
	if User.Id == 0 {
		response.ResponseError(c, "注册失败", nil)
		return
	}
	response.ResponseSuccess(c, "注册成功", User)
}

func Login(c *gin.Context) {
	var data request.RegisterAdd
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	var user model.User
	dao.Where(&model.User{Name: data.Name}, &user)
	if user.Id == 0 {
		response.ResponseError(c, "用户不存在", nil)
		return
	}
	claims := jwt.CustomClaims{ID: user.Id}
	token, err := jwt.NewJWT(JWT_USER_DON).CreateToken(claims)
	if err != nil {
		response.ResponseError(c, "token生成失败", err)
		return
	}
	response.ResponseSuccess(c, "登录成功", token)
}
